package common

import (
	"errors"

	"github.com/chinahdkj/xorm"
)

//XormPlusService XORM相关的服务
type XormPlusService struct {
	Engine *xorm.Engine
}

//POST RESTful - create object
func (s XormPlusService) POST(bean interface{}) error {
	_, err := s.Engine.Insert(bean)
	return err
}

//PUT RESTful - edit object
func (s XormPlusService) PUT(id interface{}, bean interface{}, result interface{}) error {

	affected, err := s.Engine.Where("id=?", id).Update(bean)

	if affected > 0 {
		_, err := s.Engine.Id(id).Get(result)
		return err
	}

	return err
}

//DELETE RESTful - delete object
func (s XormPlusService) DELETE(id interface{}, result interface{}) error {
	_, err := s.Engine.Where("id=?", id).Delete(result)
	return err
}

//GET RESTful - get object
func (s XormPlusService) GET(id interface{}, result interface{}) error {

	_, err := s.Engine.Where("id=?", id).Get(result)
	return err
}

func (s XormPlusService) QueryMap(in interface{}, result interface{}, p interface{}) (err error) {
	var ok bool
	var r []map[string]interface{}
	var a *[]map[string]interface{}

	var sql string
	var params []interface{}

	sql = in.(string)
	params = p.([]interface{})
	if len(params) > 0 {
		r, err = s.Engine.Sql(sql, params...).Query().List()
	} else {
		r, err = s.Engine.Sql(sql).Query().List()
	}

	if err != nil {
		return err
	}

	if a, ok = result.(*[]map[string]interface{}); !ok {
		err = errors.New("xormplus.QueryMap result 类型转换失败.")
		return
	}

	*a = r
	return nil
}

//sql分页查询
func (s XormPlusService) QueryMapPage(in interface{}, result interface{}, p interface{}, page int, size int, allRecord int) (err error) {
	var ok bool
	var r []map[string]interface{}
	var a *[]map[string]interface{}

	var sql string
	var params []interface{}

	sql = in.(string)
	params = p.([]interface{})

	firstResult := (page-1)*size + 1
	maxResult := (page-1)*size + size

	if maxResult > allRecord {
		maxResult = allRecord
	}

	if len(params) > 0 {
		r, err = s.Engine.Sql(sql, params...).Query().ListPage(firstResult, maxResult)
	} else {
		r, err = s.Engine.Sql(sql).Query().ListPage(firstResult, maxResult)
	}

	if err != nil {
		return err
	}

	if a, ok = result.(*[]map[string]interface{}); !ok {
		err = errors.New("xormplus.QueryMap result 类型转换失败.")
		return
	}

	*a = r
	return nil
}
